const Router = require('koa-router');
const router = new Router();
const {db, QueryTypes} = require("../../models/db");

// 保存送货路线区域
router.post('/deliver/getGoodByCode', async ctx => {
    let tenantId = ctx.user.tenantId;
    let code = ctx.request.body.code
    let good = await db.models['goods'].findOne({
        where: {
            tenantId,
            barCode: code,
        }
    })
    if(good) {
        //
        let sqls = `select top 1 unit, price from v_price_his_last where tenantId=${tenantId} and 
                              transType=150601 and buId=(select top 1 id from contact where name=N'零售客户') 
                            and isnull(price,0)<>0 and unit='${good.unit1}' order by id desc 
        
        `
        let priceModel = await db.query(sqls, {type: QueryTypes.SELECT, plain: true})
        return ctx.suc('', {
            id: good.id,
            name: good.name,
            spec: good.spec,
            unit: good.unit1,
            unit1: good.unit1,
            unit2: good.unit2,
            price: priceModel?priceModel.price:good.price2
        })
    }
    else {
        let good1 = await db.models['goods'].findOne({
            where: {
                tenantId,
                barCode1: code,
            }
        })
        if(good1) {
            if(good.unit2) {
                return ctx.err('该条码为小单位条码，但该商品还没有设置小单位')
            }
            let sqls = `select top 1 unit, price from v_price_his_last where tenantId=${tenantId} and 
                              transType=150601 and buId=(select top 1 id from contact where name=N'零售客户') 
                            and isnull(price,0)<>0 and unit='${good.unit2}' order by id desc 
        `
            let priceModel = await db.query(sqls, {type: QueryTypes.SELECT, plain: true})
            return ctx.suc('', {
                id: good.id,
                name: good.name,
                spec: good.spec,
                unit: good.unit2,
                unit1: good.unit1,
                unit2: good.unit2,
                price: priceModel?priceModel.price:(good.price2/good.spec)
            })
        }
        else {
            return ctx.err('没有该商品条码')
        }
    }
})

module.exports = router;
